import { defineComponent, PropType, onMounted, ref } from 'vue';
import { useNamespace } from '@ibiz-template/vue3-util';
import { IModal } from '@ibiz-template/runtime';
import './pdf-preview.scss';
import { RuntimeError } from '@ibiz-template/core';

export const PDFPreview = defineComponent({
  props: {
    modal: { type: Object as PropType<IModal>, required: true },
    file: { type: Object as PropType<IParams>, required: true },
    downloadUrl: { type: String, default: '' },
  },
  setup(props) {
    const ns = useNamespace('pdf-preview');
    const pdfContainerRef = ref();
    const loading = ref(true);

    /** 绘制页 */
    const renderPage = (pdf: IParams, pageNum: number): void => {
      pdf.getPage(pageNum).then((page: IParams) => {
        const containerWidth = pdfContainerRef.value?.clientWidth || 0; // 获取容器宽度
        const a4Width = 794; // A4纸宽度（96 DPI下，单位：像素）
        const maxWidth = Math.min(containerWidth - 32, a4Width); // 确保宽度不超过 A4 的宽度
        const scale = maxWidth / page.getViewport({ scale: 1 }).width; // 根据容器宽度和 A4 宽度计算比例
        const viewport = page.getViewport({ scale });

        const div = document.createElement('div');
        div.classList.add(ns.e('page'));
        const canvas = document.createElement('canvas');
        canvas.classList.add(ns.em('page', 'content'));
        canvas.width = viewport.width;
        canvas.height = viewport.height;

        div.appendChild(canvas);
        pdfContainerRef.value?.appendChild(div);

        const context = canvas.getContext('2d');
        page.render({ canvasContext: context, viewport }).promise.then(() => {
          // 绘制成功
        });
      });
    };

    /** 绘制pdf */
    const renderPDF = async (url: string): Promise<void> => {
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      const loadingTask = (window as any).pdfjsLib.getDocument(url);
      const pdf = await loadingTask.promise;
      const totalPages = pdf.numPages;
      for (let pageNum = 1; pageNum <= totalPages; pageNum++) {
        renderPage(pdf, pageNum);
      }
      loading.value = false;
    };

    const handlePDF = async (url: string): Promise<void> => {
      // 发送get请求
      const response = await ibiz.net.request(url, {
        method: 'get',
        responseType: 'blob',
        baseURL: '', // 已经有baseURL了，这里无需再写
      });

      if (response.status !== 200) {
        throw new RuntimeError(ibiz.i18n.t('runtime.platform.failedDownload'));
      }
      // 请求成功，后台返回的是一个文件流
      if (!response.data) {
        throw new RuntimeError(ibiz.i18n.t('runtime.platform.fileStreamData'));
      } else {
        // 用blob对象获取文件流
        const blob = new Blob([response.data as Blob], {
          type: 'application/pdf',
        });
        const tempUrl = URL.createObjectURL(blob);
        renderPDF(tempUrl);
      }
    };
    const dataProcess = (): void => {
      const { file, downloadUrl } = props;
      const url = file.url || downloadUrl.replace('%fileId%', file.id);
      handlePDF(url);
    };

    onMounted(() => {
      dataProcess();
    });

    return {
      ns,
      pdfContainerRef,
      loading,
    };
  },
  render() {
    return (
      <div class={this.ns.b()} v-loading={this.loading}>
        <div class={this.ns.e('scroll-container')}>
          <div class={this.ns.e('container')} ref='pdfContainerRef'></div>
        </div>
      </div>
    );
  },
});
